--[[
	
	Name: Advanced Questbook
	By: Crypton

Originally I was attempting to utilize a new channel that was created
automatically when the first person pinged for quest requests. The new
data channel was created, players who had AQB Share active joined and
the channel was able to be successfully hidden and data passed back and
forth to share quest information.

The problem is it seems player created channels are not very reliable.
Often, something as simple as reloading the UI could break the data chain.

There were many other issues with it as well, often share would for no
reason just stop working while few others would continue to share data.

To remedy this, I have instead adopted use of the whisper system. Since it
seems this is more reliable and you do not have to create or track a channel,
who was channel owner, password to protect the channel from intrusion of non
party members, etc..

Whisper seems to be working out nicely, but I still have much work to do to
automate a lot of it such as auto updating shares, etc.. Regardless, it is
currently a functional system and is very promising for future expansion
of AQB.

Sometimes the whisper event is not hidden from the player, this is not a major
issue but is a known problem. The problem is within the way I am doing things
with flagging whisper to be hidden and because things happen so quickly sometimes
the flag is set back to false before the whisper actually happens. This occurs
more often when a lot of data is sent from one party member to another. I am not
sure at this point what to do as far as resolving that issue, but as soon as I
think up something I will test it out and hopefully eventually stomp that bug out.

I think because I am using the onupdate in a seperate lua that it may be the cause
as it may be running out of sync. I may eventually create an onupdate event here in
this lua to see, for now I am not too overly worried about it as long as it is not
game breaking currently then it is to me just a minor annoyance.

I do however plan on revisiting the issue :)

One goal of mine was to avoid using OnUpdate if possible, so far i have only had to
use one instance of it, I hope to figure out a way to do this sync of share data
without having to use it, but I may have to fallback on it.

]]
function AdvQuestBook_GetQuests(reply)
	local i;
	local tick = 0;
	local idx, catid, name, track, level, daily;
	local AQB_TOTALQUESTS = GetNumQuestBookButton_QuestBook();
	local AQB_SHARED_LIST = "";
	--local maxcount = 1;
	AdvQuestBook_GetCurrentWhisperStatus();
	for i = 1, AQB_TOTALQUESTS do
		idx, catid, name, track, level, daily = GetQuestInfo(i);
		if (not string.match(name, AQB_SSTRINGS["AQB_QUEST_COMPLETE1"])) then
			if (not AQB_IsEmpty(AQBQbyName[name], true)) then
				if (tick == 8) then
					AQB_FLAG_WHISPER = true;
					SendChatMessage(AQB_SSTRINGS["AQB_SHARE1"]..AQB_SHARED_LIST, "WHISPER", 0, reply);
					AQB_SHARED_LIST = "";
					AQB_SHARED_LIST = AQB_SHARED_LIST..AQBQbyName[name]..",";
					tick = 0;
				else
					AQB_SHARED_LIST = AQB_SHARED_LIST..AQBQbyName[name]..",";
					tick = tick + 1;
					--maxcount = maxcount + 1;
				end
			end
		end
		--if (maxcount == 16) then
			--break;
		--end
	end
	if (not AQB_IsEmpty(AQB_SHARED_LIST, true)) then
		AQB_FLAG_WHISPER = true;
		SendChatMessage(AQB_SSTRINGS["AQB_SHARE1"]..AQB_SHARED_LIST, "WHISPER", 0, reply);
	end
	-- Will have to create a queing system before doing this
	-- otherwise if a full party or raid shares quests, player
	-- will have a ton of sounds go off at one time :P
	-- Put here as a reminder for me to do later.
	-- PlaySoundByPath("sound\\interface\\");
	return;
end

function AdvQuestBook_QuestPingRequest()
	AQB_SharedQuests = {};
	SaveVariables("AQB_SharedQuests");
	SendChatMessage(AQB_SSTRINGS["AQB_PING1"], "PARTY", 0, 0);
	AQB_SENT_PING = true;
	AdvQuestBookMiniMapShareButton:Disable();
end

function AdvQuestBookQuestShare_OnLoad(this)
	this:RegisterEvent("VARIABLES_LOADED");
	this:RegisterEvent("CHAT_MSG_SYSTEM");
	this:RegisterEvent("CHAT_MSG_PARTY");
	this:RegisterEvent("CHAT_MSG_WHISPER");
	this:RegisterEvent("PARTY_MEMBER_CHANGED");
	this:RegisterEvent("CHAT_MSN_OPEN");
	this:RegisterEvent("CHAT_MSN_POPUP");
end

function AdvQuestBookQuestShare_OnEvent(this, event, aqbqs1, aqbqs2, aqbqs3, aqbqs4)
	if (event == "VARIABLES_LOADED") then
		if (AQB_IsEmpty(AQB_SharedQuests, true)) then
			AQB_SharedQuests = {};
		end
		SaveVariables("AQB_SharedQuests");
		AQB_Def_ChannelSets = {};
		AQB_CLOSE_MSN_OPEN = false;
		AQB_CLOSE_MSN_POPUP = false;
		AQB_FLAG_WHISPER = false;
		AQB_SENT_PING = false;
		if (AdvQuestBook_Config["settings"][10]["value"]) then
			if (GetNumPartyMembers() > 0) then
				if (not AdvQuestBookMiniMapShareButton:IsVisible()) then
					AdvQuestBookMiniMapShareButton:Show();
				end
			elseif (GetNumPartyMembers() <= 0) then
				AQB_SharedQuests = {};
				SaveVariables("AQB_SharedQuests");
				AQB_LAST_SHARE = 0;
				AQB_SITEM_INDEX = {};
				AQB_SITEM_DATA = {};
				AQB_SOPEN_ITEMS = 0;
			end
		end
	end
	if (not AdvQuestBook_Config["settings"][10]["value"]) then
		if (AdvQuestBookMiniMapShareButton:IsVisible()) then
			AdvQuestBookMiniMapShareButton:Hide();
		end
		return;
	end
	if (event == "CHAT_MSG_PARTY") then
		if (string.find(aqbqs1, AQB_SSTRINGS["AQB_PING2"])) then
			if (aqbqs4 ~= UnitName("player")) then
				AdvQuestBook_GetQuests(aqbqs4);
				AQB_CLOSE_MSN_OPEN = true;
			elseif (aqbqs4 ~= UnitName("player")) then
				AQB_CLOSE_MSN_POPUP = true;
			end
		end
	elseif (event == "CHAT_MSG_WHISPER") then
		if (string.find(aqbqs1, AQB_SSTRINGS["AQB_SHARE2"])) then
			AdvQuestBook_GetCurrentWhisperStatus();
			AQB_CLOSE_MSN_POPUP = true;
			local inshare = false;
			local pidx;
			local csv = string.gsub(aqbqs1, AQB_SSTRINGS["AQB_SHARE2"], "");
			local qmatch;
			local playershared = table.getn(AQB_SharedQuests);
			local breakid = 0;
			for pidx = 1, playershared do
				if (not AQB_IsEmpty(AQB_SharedQuests[pidx], true)) then
					if (not AQB_IsEmpty(AQB_SharedQuests[pidx]["name"], true)) then
						if (AQB_SharedQuests[pidx]["name"] == aqbqs4) then
							inshare = true;
							break;
						end
					end
				end
			end
			if (not inshare) then
				local playertable = {
					["name"] = aqbqs4,
					["quests"] = {},
				};
				table.insert(AQB_SharedQuests, playertable);
			end
			playershared = table.getn(AQB_SharedQuests);
			for pidx = 1, playershared do
				if (not AQB_IsEmpty(AQB_SharedQuests[pidx], true)) then
					if (not AQB_IsEmpty(AQB_SharedQuests[pidx]["name"], true)) then
						if (AQB_SharedQuests[pidx]["name"] == aqbqs4) then
							breakid = pidx;
							break;
						end
					end
				end
			end
			if (breakid ~= 0) then
				AdvQuestBook_ConvertCSV(csv, AQB_SharedQuests[breakid]["quests"]);
			end
			AQB_FLAG_WHISPER = true;
			if (AQB_SENT_PING) then
				AQB_SENT_PING = false;
				DEFAULT_CHAT_FRAME:AddMessage("|cFFffffff"..AQB_ISTRINGS["AQB_LIST_RECIEVED"].."|r");
				AdvQuestBookMiniMapShareButton:Enable();
			end
		end
	elseif (event == "CHAT_MSN_OPEN") then
		if (AQB_CLOSE_MSN_OPEN) then
			local popup = getglobal("CRG_Chat"..aqbqs1);
			popup:Hide();
			AQB_CLOSE_MSN = false;
		end
	elseif (event == "CHAT_MSN_POPUP") then
		if (AQB_CLOSE_MSN_POPUP) then
			local popup = getglobal("CRG_Chat"..aqbqs1);
			popup:Hide();
			AQB_CLOSE_MSN_POPUP = false;
		end
	elseif (event == "PARTY_MEMBER_CHANGED") then
		if (AQB_DEBUG_GAMESTRINGS) then
			local evstring = AdvQuestBook_DebugArgs(event, aqbqs1, aqbqs2, aqbqs3, aqbqs4);
			if (evstring ~= nil) then
				table.insert(AQB_DEBUG_LANG_STRINGS[AQB_LOCAL], "EVString: "..evstring);
				SaveVariables("AQB_DEBUG_LANG_STRINGS");
			end
		end
		if (GetNumPartyMembers() > 0) then
			if (not AdvQuestBookMiniMapShareButton:IsVisible()) then
				AdvQuestBookMiniMapShareButton:Show();
			end
		elseif (GetNumPartyMembers() <= 0 and AdvQuestBookMiniMapShareButton:IsVisible()) then
				AdvQuestBookMiniMapShareButton:Hide();
				AQB_SharedQuests = {};
				SaveVariables("AQB_SharedQuests");
				AQB_LAST_SHARE = 0;
				AQB_SITEM_INDEX = {};
				AQB_SITEM_DATA = {};
				AQB_SOPEN_ITEMS = 0;
		end
	elseif (event == "CHAT_MSG_SYSTEM") then
		if (AQB_DEBUG_GAMESTRINGS) then
			local evstring = AdvQuestBook_DebugArgs(event, aqbqs1, aqbqs2, aqbqs3, aqbqs4);
			if (evstring ~= nil) then
				table.insert(AQB_DEBUG_LANG_STRINGS[AQB_LOCAL], "EVString: "..evstring);
				SaveVariables("AQB_DEBUG_LANG_STRINGS");
			end
		end
		if (string.find(aqbqs1, AQB_SSTRINGS["PARTY_YOU_LEFT"])) then
			AQB_SharedQuests = {};
			SaveVariables("AQB_SharedQuests");
			AQB_LAST_SHARE = 0;
			AQB_SITEM_INDEX = {};
			AQB_SITEM_DATA = {};
			AQB_SOPEN_ITEMS = 0;
		elseif (string.find(aqbqs1, AQB_SSTRINGS["PARTY_MEMBER_LEAVES"])) then
			local player = string.gsub(aqbqs1, AQB_SSTRINGS["PARTY_MEMBER_LEAVES"], "");
			player = string.gsub(player, AQB_SSTRINGS["PARTY_LBRACKET"], "");
			player = string.gsub(player, AQB_SSTRINGS["PARTY_RBRACKET"], "");
			if (player ~= UnitName("player")) then
				local pidx;
				local breakid = 0;
				local tmptable = AQB_SharedQuests;
				local playershared = table.getn(AQB_SharedQuests);
				local i, v;
				AQB_SharedQuests = {};
				for i, v in pairs(tmptable) do
					if (v["name"] ~= player) then
						table.insert(AQB_SharedQuests, v);
					end
				end
				SaveVariables("AQB_SharedQuests");
			end
		end
	end
end

function AdvQuestBookQuestShare_OnUpdate(curtimer)
	if (AQB_FLAG_WHISPER) then
		AdvQuestBook_SetCurrentWhisperStatus();
	end
	AQB_TTW = AQB_TTW - curtimer;
	if (AQB_TTW <= 0) then
		if (not AQB_SharedQuests) then
			AQB_SharedQuests = {};
		end
		local countshare = table.getn(AQB_SharedQuests);
		if (AQB_SENT_PING and countshare <= 0) then
			AQB_SENT_PING = false;
			DEFAULT_CHAT_FRAME:AddMessage("|cFFffffff"..AQB_ISTRINGS["AQB_NOLIST_RECIEVED"].."|r");
		end
		AQB_TTW = 3;
		AdvQuestBookMiniMapShareButton:Enable();
	end
end
